package org.freemarker.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freemarker.core.model.Car;
import org.freemarker.core.service.CarService;
import org.freemarker.web.custom.CustomHttpServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class CarDeleteController extends CustomHttpServlet {

	private static final long serialVersionUID = 5923553639902965003L;

	@Autowired
	private CarService carService;
	
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.getRequestDispatcher("views/car/deleteCar.ftl").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String numarMatricol = req.getParameter("numarMatricol");
		
		Car c=new Car();
		String delError = new String();
		try {
			c = carService.getCarForNr(numarMatricol);
		} catch (Exception e) {
			delError="Car not present in database!";
			List<Car> cars = carService.findAll();
			req.setAttribute("cars", cars);
			req.setAttribute("delError",delError);
			req.getRequestDispatcher("views/car/listCars.ftl")
					.forward(req, res);
			return;
		}

		carService.deleteById(c.getId());
		List<Car> cars = carService.findAll();

		req.setAttribute("cars", cars);
		req.getRequestDispatcher("views/car/listCars.ftl")
				.forward(req, res);
	}

	
}
